package com.htht.smartschool.common.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.htht.smartschool.model.bigexam.AdminExamResultBean;
import com.htht.smartschool.model.bigexam.BigExamBean;
import com.htht.smartschool.model.bigexam.ParentExamBean;
import com.htht.smartschool.model.bigexam.ParentExamResultBean;
import com.htht.smartschool.model.bigexam.SubjectInfoBean;
import com.htht.smartschool.model.bigexam.TeacherExamResultBean;
import com.htht.smartschool.model.bigexam.TotalListBean;
import com.htht.smartschool.service.bigexam.BigExamService;
import com.htht.smartschool.service.bigexam.ResultService;
import com.htht.smartschool.util.createBean.DynamicBean;
import com.htht.smartschool.util.system.ExportExcel;



public class ResultExportServlet extends HttpServlet{
	ExportExcel exportExcel = new ExportExcel();
	/**
	 * Constructor of the object.
	 */

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ResultService resultService = new ResultService();
		response.setContentType("text/html");
		boolean flag = false;
		String cmd = request.getParameter("cmd");
		String coursecode = request.getParameter("coursecode");
		String examcode=request.getParameter("examcode");
		String schoolcode=request.getParameter("schoolcode");
		String schooltype=request.getParameter("schooltype");
		String classcode=request.getParameter("classcode");
		String grades = request.getParameter("grades");
		String studentcode = request.getParameter("studentcode");
		String path = request.getParameter("path");
		String fileName = request.getParameter("fileName");
		//设置响应头  用户点击后形成一个下载窗口，让用户保存
		response.addHeader("Content-Disposition", "attachment;filename="  
                + new String(fileName.getBytes("gb2312"),"ISO8859-1")+".xls");  
        OutputStream toClient = new BufferedOutputStream(  
                response.getOutputStream());  
        response.setContentType("application/vnd.ms-excel;charset=gb2312");  
		OutputStream out = response.getOutputStream();
		PrintWriter print = null;
		ExportExcel xportExcel = new ExportExcel();
		if(cmd.equalsIgnoreCase("getEveryExamInfo")){//导出管理员  教师端 查看每科考试学生成绩的信息
			//弹出对话框
//			String adr = exportExcel.selectSavePath();
			List<AdminExamResultBean> list = resultService.getEveryExamInfo(coursecode,examcode,schoolcode,schooltype,classcode,grades);
			String[] headers = {"姓名","学号","分数","年级","科目","校排名","班内排名"};
			ExportExcel<AdminExamResultBean> ex = new ExportExcel<AdminExamResultBean>();
			String examname = list.get(0).getSubjectname();
			ex.exportExcel(examname,headers, list, out);
			try {
				out.close();
				toClient.flush();
				toClient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}else if(cmd.equalsIgnoreCase("getTeacherResultList")){//导出教师端 成绩列表excel
			List<TeacherExamResultBean> list = resultService.getTeacherResultList(examcode,studentcode,classcode);
			String[] headers = {"姓名","学号","分数","年级","考试名称","班内排名"};
			ExportExcel<TeacherExamResultBean> ex = new ExportExcel<TeacherExamResultBean>();
			String examname =  list.get(0).getExamname();
			ex.exportExcel(examname,headers, list, out);
			try {
				out.close();
				toClient.flush();
				toClient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}else if(cmd.equalsIgnoreCase("getParentChildrenOneEXamResult")){//导出家长端一科成绩成绩单详情
			List<ParentExamResultBean> list = resultService.getParentChildrenOneEXamResult(coursecode,examcode,schoolcode,schooltype,classcode,grades,studentcode);
			String[] headers = {"姓名","学号","分数","年级","学科","校排名","班内排名"};
			ExportExcel<ParentExamResultBean> ex = new ExportExcel<ParentExamResultBean>();
			String examname =  list.get(0).getSubjename();
			ex.exportExcel(examname,headers, list, out);
			try {
				out.close();
				toClient.flush();
				toClient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}else if(cmd.equalsIgnoreCase("getExamTotalList")){//导出总榜信息
			List<TotalListBean> result = resultService.getExamTotalList(examcode,schoolcode,grades,classcode);
			
			//---------------snow start----------------
			StringBuffer buffer=new StringBuffer();
			String title="";
			buffer.append("姓名,学号,班级");
			if(result!=null&&result.size()>0){
				TotalListBean bean=result.get(0);
				if(bean.getSubjectinfo()!=null && bean.getSubjectinfo().size()>0){
					for(SubjectInfoBean sub:bean.getSubjectinfo()){
					buffer.append(","+sub.getSubject());
					}
				}
				title=result.get(0).getExamname()+"的";
			}
				buffer.append(",总分,校排名,班内排名");
		        String[] headers = buffer.toString().split(",");
		        
		     //---------------------snow end---------------
		        DynamicBean  dynam = new DynamicBean();
				 // 设置类成员属性  
		        List<LinkedHashMap> list = new ArrayList<LinkedHashMap>();
		        try{
					for(int j = 0;j<result.size();j++){
						LinkedHashMap bean = new LinkedHashMap();
						//BigExamBean exam = result.get(j);
						 bean.put("studentname",result.get(j).getStudentname());
			        	 bean.put("studentcode",result.get(j).getStudentcode());
			        	 bean.put("classesname",result.get(j).getClassesname());
			        	 
			        	 for(int k=0;k<result.get(j).getSubjectinfo().size();k++){
			        		bean.put(headers[k+3], result.get(j).getSubjectinfo().get(k).getScore().toString());
			        	 }
			        	 bean.put("scorenumber", result.get(j).getScorenumber());
			        	 bean.put("schoolrank",result.get(j).getSchoolrank());
			        	 bean.put("classranking",result.get(j).getClassranking());
					        list.add(bean);
			        	 }
		        }catch(Exception e){
						e.printStackTrace();
					}
				ExportExcel<LinkedHashMap> ex = new ExportExcel<LinkedHashMap>();
				System.out.println(title);
				ex.exportExcel(title+"总榜成绩",headers, list, out,"yes");
				try {
					out.close();
					toClient.flush();
					toClient.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}

		        }else if(cmd.equalsIgnoreCase("getParentChildrenOneExamRank")){//导出家长端成绩榜
		        	List<ParentExamBean> result = resultService.getParentChildrenOneExamRank(examcode,studentcode,schoolcode,classcode,grades);
		        	StringBuffer buffer=new StringBuffer();
					buffer.append("姓名,学号,班级");
					if(result!=null&&result.size()>0){
						ParentExamBean bean=result.get(0);
						if(bean.getSubjectinfo()!=null && bean.getSubjectinfo().size()>0){
							for(SubjectInfoBean sub:bean.getSubjectinfo()){
							buffer.append(","+sub.getSubject());
							}
						}
					}
						buffer.append(",校排名");
				        String[] headers = buffer.toString().split(",");
				        
				     //---------------------snow end---------------
				        DynamicBean  dynam = new DynamicBean();
						 // 设置类成员属性  
				        List<LinkedHashMap> list = new ArrayList<LinkedHashMap>();
				        try{
							for(int j = 0;j<result.size();j++){
								LinkedHashMap bean = new LinkedHashMap();
								//BigExamBean exam = result.get(j);
								 bean.put("studentname",result.get(j).getStudentname());
					        	 bean.put("studentcode",result.get(j).getStudentcode());
					        	 bean.put("classesname",result.get(j).getClassesname());
					        	 
					        	 for(int k=0;k<result.get(j).getSubjectinfo().size();k++){
					        		bean.put(headers[k+3], result.get(j).getSubjectinfo().get(k).getScore().toString());
					        	 }
					        	 bean.put("schoolrank",result.get(j).getSchoolrank());
							        list.add(bean);
					        	 }
				        }catch(Exception e){
								e.printStackTrace();
							}
						ExportExcel<LinkedHashMap> ex = new ExportExcel<LinkedHashMap>();
						String examname = result.get(0).getExamname();
						ex.exportExcel(examname,headers, list, out,"yes");
						try {
							out.close();
							toClient.flush();
							toClient.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
		        }

		        
	}
	private void download(String path, HttpServletResponse response) {  
        try {  
            // path是指欲下载的文件的路径。  
            File file = new File(path);  
            // 取得文件名。  
            String filename = file.getName();  
            // 以流的形式下载文件。  
            InputStream fis = new BufferedInputStream(new FileInputStream(path));  
            byte[] buffer = new byte[fis.available()];  
            fis.read(buffer);  
            fis.close();  
            // 清空response  
            response.reset();  
            // 设置response的Header  
            response.addHeader("Content-Disposition", "attachment;filename="  
                    + new String(filename.getBytes()));  
            response.addHeader("Content-Length", "" + file.length());  
            OutputStream toClient = new BufferedOutputStream(  
                    response.getOutputStream());  
            response.setContentType("application/vnd.ms-excel;charset=gb2312");  
            toClient.write(buffer);  
            toClient.flush();  
            toClient.close();  
        } catch (IOException ex) {  
            ex.printStackTrace();  
        }  
    }  

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	}
